//
//  M4String.swift
//  M4
//
//  Created by YuChuang on 2024/8/16.
//

import UIKit

class M4String: NSObject {
    
    static func M4StringBlank(originalStr: String, per: Int = 4, charact: String = " ") -> String {
        var modifiedStr = ""
        for (index, char) in originalStr.enumerated() {
            if index > 0 && index % per == 0 {
                modifiedStr += charact
            }
            modifiedStr += String(char)
        }
        return modifiedStr
    }


    static func M4BlankAmount(original: String, per: Int = 3, charact: Character = ",", sort: String = "back") -> String {
        let spaceCount = Int(original.count/per)
        var resultString = original
        guard spaceCount >= 1 else {
            return original
        }
        for i in 1...spaceCount {
            var offset = 0
            if sort == "back" {
                offset = resultString.count-per*i
            }
            else {
                offset = per*i+(i-1)
            }
            guard offset != 0 else {break}
            resultString.insert(charact, at: resultString.index(resultString.startIndex, offsetBy: offset))
        }
        return resultString
    }
    
    static func M4JSONStringFromDict(dictionary:Any) -> String {
        if(!JSONSerialization.isValidJSONObject(dictionary)) {
            print("fail to JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    static func M4TimeStampToString(timeStamp: Int)->String {
        
        let days = Int(timeStamp/(3600*24))
        
        let hours = Int((timeStamp - days*24*3600)/3600)
        
        let minute = Int((timeStamp - days*24*3600-hours*3600)/60)
        
        let second = Int((timeStamp - days*24*3600-hours*3600) - 60*minute)
        var timeString = ""
        if days > 0 {
            timeString = String.init(format: "%d día y %02d:%02d:%02d", days,hours,minute,second)
            return timeString
        }
        else if hours > 0 {
            timeString = String.init(format: "%d:%02d:%02d", hours,minute,second)
            return timeString
        }
        else if minute > 0 {
            timeString = String.init(format: "%02d:%02d", minute,second)
            return timeString
        }
        else {
            timeString = String.init(format: "%02d:%02d", minute,second)
            return timeString
        }
    }

}
